<template>
  <div class="xh-content">
    <!-- 提示 -->
    <section v-if="status === 1" class="xh-message-text">{{ message }}</section>
    <!-- 显示短链接和二维码图片 -->
    <section v-if="status === 3" class="xh-clink">
      <div class="short-link">
        短链接：<a :href="shortUrl" class="short-link-text">{{ shortUrl }}</a>
      </div>
      <div class="short-qrcode">
        二维码：
        <span ref="qrcode" />
      </div>
    </section>
  </div>
</template>
<script>
import QRCode from "QRCode";
export default {
  data() {
    return {
      status: 0, // 0 none 1 error 2 loading 3 finished
      message: "",
      loading: null,
      shortUrl: "",
      QRCode: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.$bus.$on("sendLongUrl", (config) => {
        const { longUrl, message, status } = config;
        this.status = 0;
        this.message = "未知的错误！";
        this.QRCode && (this.$refs.qrcode.innerHTML = "");
        if (!status) {
          this.message = message;
          this.status = 1;
        } else {
          this.status = 2; // 发送请求
          this.requestShortUrl(longUrl);
        }
      });
    },
    requestShortUrl(link) {
      this.loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      fetch("http://www.sphjy.com/api/url/shorten", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          longURL: link,
        }),
      })
        .then((res) => res.json())
        .then((res) => {
          this.status = 3;
          this.shortUrl = res.shortUrl;
          // 生成二维码
          this.getQRCode();
        })
        .catch((e) => {
          this.status = 1;
          this.message = e.message;
        })
        .finally(() => {
          this.loading.close();
          this.loading = null;
        });
    },
    getQRCode() {
      this.$nextTick(() => {
        this.QRCode = new QRCode(this.$refs.qrcode, {
          text: this.shortUrl,
          width: 128,
          height: 128,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H,
        });
      });
    },
  },
};
</script>
<style scoped lang="stylus">
.xh-content {
  width: 800px;
  margin: 0 auto;
}

.short-link {
  height: 80px;
  align-items: center;
  display: flex;
  text-align: left;
}

.short-qrcode {
  height: 150px;
  align-items: center;
  display: flex;
  text-align: left;
}
</style>
